package com.futvan.z.system.zfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.ImgUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.SystemUtil;
import com.futvan.z.system.zfile.ZfileService;
@Controller
public class ZfileAction extends SuperAction{
	@Autowired
	private ZfileService zfileService;

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value="/upload")
	public @ResponseBody Result upload(String filepath,HttpServletRequest request){
		Result result = new Result();
		String fileReturnPath = "";
		List<String> uploadFileList = new ArrayList<String>();
		try {
			//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
			CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
			//检查form中是否有enctype="multipart/form-data"
			if(multipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
				//获取multiRequest 中所有的文件名
				Iterator iter=multiRequest.getFileNames();
				while(iter.hasNext()){
					//一次遍历所有文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){
						//创建保存路径
						String fileSavePath = CreateFileSavePath(filepath);
						
						//保存文件
						save(file,fileSavePath+"/"+file.getOriginalFilename());
						
						//创建返回URL
						fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+file.getOriginalFilename();
						uploadFileList.add(fileReturnPath);
						
						//如果是图片，返回压缩图片路径
						if(ImgUtil.isImg(file.getOriginalFilename())) {
							String z1_fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z1." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
							uploadFileList.add(z1_fileReturnPath);
							
							String z5_fileReturnPath = z.sp.get("fileserverurl")+"/files/"+filepath+"/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) +"_z5." + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); 
							uploadFileList.add(z5_fileReturnPath);
						}
						
						
						//保存文件名到数据库
						zfileService.save(fileReturnPath,filepath,z.sp.get("fileserverurl"),file);
					}
				}
			}
			result.setCode(Code.SUCCESS);
			result.setMsg(JsonUtil.listToJson(uploadFileList));
			result.setData(fileReturnPath);
		} catch (Exception e) {
			result.setCode(Code.ERROR);
			result.setMsg("file upload error："+e.getMessage());
			result.setData(e.getMessage());
		} 
		return result;
	}

	private String CreateFileSavePath(String filepath) throws Exception{
		String fileSavePath = "";
		String project_path = System.getProperty("web.root");
		if(!"".equals(project_path) && project_path!=null) {
			fileSavePath = project_path;
			//判读路径是否为空
			if(!"".equals(filepath) && filepath!=null) {
				fileSavePath = fileSavePath+"/files/"+filepath;
			}

			// 判断文件目录是否存在如果不存在怎么创建
			File dir = new File(fileSavePath);
			if (!dir.exists() && !dir.isDirectory()) {
				//创建多级目录
				dir.mkdirs();
			}
		}else {
			throw new Exception("文件服务器系统错误:创建文件保存路径出错。请稍后上传。");
		}
		return fileSavePath;
	}

	/**
	 * 保存文件
	 * @throws Exception
	 */
	private void save(MultipartFile file,String fileSavePath) throws Exception{
		file.transferTo(new File(fileSavePath));

		//同时生成压缩文件
		ImgUtil.ImgZip(fileSavePath);
	}
}
